package com.test.json;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonUtil {
	
	public static JSONObject getJsonObject(String url){
		
		try {
			return new JSONObject(getJsonString(url));
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static String getJsonString(String url){
		
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse httpResponse;
		InputStream inputStream = null;
		ByteArrayOutputStream bo = null;
		try {
			httpResponse = httpClient.execute(httpGet);
			if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				inputStream = httpResponse.getEntity().getContent();
				bo = new ByteArrayOutputStream();
				for (int i = -1; (i = inputStream.read()) != -1;) {
					bo.write(i);
				}
			}
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return "";
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
		
		return bo.toString();
	}

}
